package alternate;

/**
 * @author wcj
 * @Date 2021/7/22 11:37
 * @Version 1.0
 */
public class SynchronizedImpl {

    private static volatile int count = 1;
    private static final Object obj = new Object();

    public static void main(String[] args) {

        // 奇数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 如果被中断，直接退出
                    boolean isInterrupt = Thread.currentThread().isInterrupted();
                    if (isInterrupt) {
                        break;
                    }
                    // 真正的线程同步处
                    synchronized (obj) {
                        // 如果count超过100
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 1) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                    }
                }
            }
        }, "奇数线程").start();

        // 偶数线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    // 如果中断，退出
                    boolean interrupted = Thread.currentThread().isInterrupted();
                    if (interrupted) {
                        break;
                    }
                    synchronized (obj) {
                        // count超出值范围
                        if (count > 100) {
                            break;
                        }
                        if (count % 2 == 0) {
                            System.out.println(Thread.currentThread().getName() + ":" + count++);
                        }
                    }
                }
            }
        }, "偶数线程").start();
    }
}
